package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.commom.PageResult;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.commom.UserIdContext;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.entity.YddUserData;
import com.itheima.ydd.service.YddArticleService;
import com.itheima.ydd.service.YddUserDataService;
import com.itheima.ydd.service.YddUserService;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class FrontUserController {
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddUserDataService yddUserDataService;

    /**
     * 前台用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("getUserInfo")
    public R getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        //解析token
        Claims claims = JwtUtils.getClaims(token);
        //获取用户的信息
        Integer userId = (Integer) claims.get("userId");

        log.info("当前用户的id为：{}", userId);

        //通过当前用户的id获取信息
        Map map = new HashMap();
        map.put("userInfo", yddUserService.getById(userId));

        map.put("articleNum", yddArticleService.count(new LambdaQueryWrapper<YddArticle>().eq(YddArticle::getUserId, userId)));

        map.put("zanNum", yddUserDataService.count(
                new LambdaQueryWrapper<YddUserData>()
                        .eq(YddUserData::getUserId, userId)
                        .eq(YddUserData::getType, 2)
        ));
        map.put("collectNum", yddUserDataService.count(
                new LambdaQueryWrapper<YddUserData>()
                        .eq(YddUserData::getUserId, userId)
                        .eq(YddUserData::getType, 1)
        ));

        return R.success("", map);
    }

    /**
     * 前台获取用户数据
     *
     * @param page
     * @param limit
     * @param type
     * @return
     */
    @GetMapping("/userDataList")
    public R getUserData(Integer page, Integer limit, String type) {
        //获取当前登录用户的id信息
        String userId = UserIdContext.getCurrentId();
        LambdaQueryWrapper<YddUserData> dataWrapper = new LambdaQueryWrapper<>();
        dataWrapper.eq(YddUserData::getUserId, userId);
        dataWrapper.eq(YddUserData::getType, type);
        List<YddUserData> list = yddUserDataService.list(dataWrapper);
        List<Integer> articleId = new ArrayList<>();
        if (list == null || list.size() == 0) {
            return R.success("查询为空", null);
        }

        for (YddUserData yddUserData : list) {
            articleId.add(yddUserData.getArticleId());
        }
        Page<YddArticle> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.in(YddArticle::getId, articleId);
        //根据时间降序排列
        articleWrapper.orderByAsc(YddArticle::getCreateDate);
        yddArticleService.page(pageInfo, articleWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setCount(pageInfo.getTotal());
        pageResult.setCurrentPage(pageInfo.getCurrent());
        pageResult.setPageSize(pageInfo.getSize());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setData(pageInfo.getRecords());

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageResult);
        return R.success("", map);
    }

    /**
     * 查询前端登录用户的文章信息
     *
     * @param limit
     * @return
     */
    @GetMapping("/myArticle")
    public R myArticle(Integer page, Integer limit) {
        LambdaQueryWrapper<YddArticle> articleWrapper = new LambdaQueryWrapper<>();
        Page<YddArticle> pageInfo = new Page<>(page, limit);
        String userId = UserIdContext.getCurrentId();
        articleWrapper.eq(YddArticle::getUserId, userId);
        articleWrapper.orderByDesc(YddArticle::getCreateDate);
        yddArticleService.page(pageInfo, articleWrapper);

        PageResult pageResult = new PageResult();
        pageResult.setCount(pageInfo.getTotal());
        pageResult.setCurrentPage(pageInfo.getCurrent());
        pageResult.setPageSize(pageInfo.getSize());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setData(pageInfo.getRecords());
        return R.success("", pageResult);
    }

    @PostMapping("addArticle")
    @CacheEvict(value = "article" , allEntries = true)
    public R addArticle(@RequestBody YddArticle yddArticle) {
        yddArticleService.save(yddArticle);
        return R.success("", "");
    }

    /**
     * 用户点赞 / 取消点赞 ；收藏 / 取消收藏
     *
     * @param type
     * @param action     依据这个参数来判断到底是执行操作还是取消操作
     * @param article_id
     * @return
     */
    @GetMapping("/userDataHandle")
    public R userDataHandle(Integer type, String action, Integer article_id) {
        if ("add".equals(action)) {
            //执行操作
            yddArticleService.addData(type, article_id);
        }

        if ("del".equals(action)) {
            //取消操作
            yddArticleService.delData(type, article_id);

        }

        return R.success("操作成功", null);
    }

    /**前台用户-修改资料
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody YddUser yddUser) {
        log.info("接收到的需要修改的参数为{}",yddUser);
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(yddUser.getId()!=null,YddUser::getId,yddUser.getId());
        yddUserService.update(yddUser,wrapper);
        return R.success("修改成功2333",yddUser);
    }
}
